import { intl } from '@/utils';
import { SettingOutlined } from '@ant-design/icons';
import { Button, Modal } from 'antd';
import SelectBox from 'devextreme-react/select-box';
import { Item } from 'devextreme-react/toolbar';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useModel } from 'umi';
import { DevToolBar } from '~/public/cpas-ui';
import AgeCalcButton, { getStartAandEndYear } from './components/AgeCalcButton';
import AgeConfigButton from './components/AgeConfigButton';
import { getInvAgeColumns } from './components/AgeConfigButton/service';
import GridTableContainer from './components/GridTableContainer';
import { AgeContext } from './context/useAgeContext';
import { ColumnFields } from './fields';
import './index.less';
import {
  calcInvAge,
  calcInvAgeStatus,
  getAccountInfo,
  getSubjectCategory,
  stopInvAge,
} from './service';

const InventoryAgeAnalysis = (props: any) => {
  const pageType = props.params?.type;
  const { initialState } = useModel('@@initialState');
  const { dbname, sjnd } = initialState?.curPart as API.CurPart;

  const [startAndEndYear, setStartAndEndYear] = useState({
    startYear: new Date().getFullYear(),
    endYear: new Date().getFullYear(),
  });
  const [accountYearData, setAccountYearData] = useState<any[]>([]);
  const [accountTreeList, setAccountTreeList] = useState<any[]>([]);
  const [statisticTypeData] = useState<any[]>([
    {
      displayName: '按汇总方式',
    },
    {
      displayName: '按批次方式',
    },
  ]);
  const [statisticType, setStatisticType] = useState<string>('按汇总方式');

  const [mountedPolling, setMountedPolling] = useState<boolean>(true); // 初始化
  const [calcLoading, setCalcLoading] = useState<boolean>(false);
  const [progressInfo, setProgressInfo] = useState({
    progressValue: 0,
    progressText: '',
    elapsedTime: '',
  });

  const timerRef = useRef<any>();

  const DataTreeRef = useRef<any>();
  const accountYearRef = useRef<any>();
  const invAgeConfigRef = useRef<any>();

  const [accountYear, setAccountYear] = useState<string>('');
  const [timeData, setTimeData] = useState<string>('');
  const [selDefaultValue, setSelDefaultValue] = useState<any>('');

  const treeData = useRef<any>([]);

  const [columnsData, setColumnsData] = useState<any[]>(ColumnFields);

  const Divstyle: React.CSSProperties = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  };
  const Titlestyle: React.CSSProperties = { marginRight: '8px' };

  const changeTimes = () => {
    setTimeData(`${new Date().getTime()}`);
  };

  const getFetchData = async () => {
    const tempYear = sjnd;
    let findTemp = -2;
    const res: any = await getAccountInfo({ dbname });
    if (res.success) {
      findTemp = res.data.findIndex((item: any) => {
        return tempYear === item.Data_ID;
      });
      const tempIndex = findTemp >= 0 ? findTemp : 0;
      const DataId = res.data[tempIndex]?.Data_ID;
      const displayNames = res.data[tempIndex]?.displayName;
      setSelDefaultValue(displayNames);
      res.data.forEach((item: any, index: any) => {
        item.index = index;
        return item;
      });
      setAccountYearData(res.data);
      accountYearRef.current = DataId;
      setAccountYear(DataId);
      const { startYear, endYear } = getStartAandEndYear(res.data);
      setStartAndEndYear({ startYear, endYear });
    }
  };

  const getInvAgeColumnsData = async () => {
    const res = await getInvAgeColumns({
      dbname,
    });
    let colTempData = columnsData;
    if (res.success) {
      if (Array.isArray(res.data) && res.data.length > 0) {
        const columns = res.data
          .filter((item) => item.isShow)
          .map((item: any) => {
            return {
              dataField: item.fieldName,
              caption: item.fieldTitle,
              dataType: 'number',
              alignment: 'right',
              allowEditing: false,
              width: 80,
            };
          });
        colTempData = colTempData.map((item: any) => {
          if (item.caption === '库龄') {
            item.columns = columns;
            return item;
          }
          return item;
        });
        setColumnsData(colTempData);
      }
    }
  };

  const clearTimer = () => {
    if (timerRef?.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  };

  const stop = async () => {
    await stopInvAge({ dbname, Data_ID: accountYear, statisticType });
  };

  const pollCalcStatus = () => {
    if (timerRef?.current) {
      clearInterval(timerRef.current);
    }
    const year = accountYear ? accountYear : accountYearRef.current;
    timerRef.current = setInterval(async () => {
      const res = await calcInvAgeStatus({
        dbname,
        Data_ID: year,
        statisticType,
      });
      if (res.success) {
        const data = res?.data;
        // const currYear = data?.year || '';
        if (data) {
          const progressInfoData = data.progressInfo || {};
          Modal.destroyAll();
          if (progressInfoData?.status === 'completed') {
            setCalcLoading(false);
            clearTimer();
            // notify(`${accountYear}库龄计算成功`, 'success', 2000);
            Modal.success({
              centered: true,
              title: `提示`,
              content: `【${startAndEndYear.startYear}-${startAndEndYear.endYear}年度区间】【${statisticType}】 库龄计算成功`,
              onOk: () => {
                changeTimes();
                stop();
              },
            });
          }
          if (['success', 'pending'].includes(progressInfoData?.status)) {
            setCalcLoading(true);
            setProgressInfo({
              progressValue: progressInfoData?.progressValue,
              progressText: progressInfoData?.progressText,
              elapsedTime: progressInfoData?.elapsedTime,
            });
          }
          if (['error', 'failed'].includes(progressInfoData?.status)) {
            clearTimer();
            setCalcLoading(false);
            setProgressInfo({
              progressValue: progressInfoData?.progressValue,
              progressText: progressInfoData?.progressText,
              elapsedTime: progressInfoData?.elapsedTime,
            });
            Modal.error({
              centered: true,
              title: `提示`,
              content: `${progressInfoData?.progressText}`,
              onOk: () => {
                stop();
              },
            });
          }
        } else {
          // clearTimer();
        }
      }
    }, 1000);
  };

  const reCalcInvAge = async () => {
    setCalcLoading(true);
    setMountedPolling(false);
    const { startYear, endYear } = startAndEndYear;
    const params = {
      dbname,
      Data_ID: accountYear,
      statisticType,
      startYear,
      endYear,
    };
    await calcInvAge(params);
    pollCalcStatus();
  };

  const onCalcOk = async () => {
    await reCalcInvAge();
  };

  // 获取树数据
  const getSubjectCategoryDatas = async () => {
    const res = await getSubjectCategory({
      dbname,
    });
    if (res.success) {
      treeData.current = res.data;
      setAccountTreeList(res.data);
    }
  };

  const reloadTreeAndTable = async () => {
    getInvAgeColumnsData();
  };

  const onSelectionChangeds = (e: any) => {
    const v: any = window.localStorage.getItem(`selectDefaultTool_${dbname}`);
    let selectDefaultIDs = JSON.parse(v);
    selectDefaultIDs = { ...selectDefaultIDs, tabledataId: e.selectedItem.Data_ID };
    // 本地存储 持久化数据
    window.localStorage.setItem(`selectDefaultTool_${dbname}`, JSON.stringify(selectDefaultIDs));
    const selectedItem = e.selectedItem;
    setAccountYear(selectedItem.Data_ID);
  };

  const onSelectionChangedStatistic = (e: any) => {
    setStatisticType(e.selectedItem.displayName);
  };

  useEffect(() => {
    getFetchData();
    getSubjectCategoryDatas();
    getInvAgeColumnsData();
  }, []);

  useEffect(() => {
    if (dbname && accountYear && mountedPolling) {
      // 开启轮训
      pollCalcStatus();
    }
    return () => {
      clearTimer();
    };
  }, [accountYear, dbname, mountedPolling]);

  const contextValue = {
    dbname,
    accountYear,
    statisticType,
  };

  return (
    <AgeContext.Provider value={contextValue}>
      <div
        className="invAge-container"
        style={{
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
        }}
      >
        <DevToolBar.Default className="ItemStyle">
          <Item location="before">
            <div style={Divstyle}>
              <div style={Divstyle}>
                <div style={Titlestyle}>{intl('report.subject.account', '账套:')}</div>
                {useMemo(() => {
                  if (selDefaultValue) {
                    return (
                      <SelectBox
                        width={240}
                        dataSource={accountYearData}
                        displayExpr="displayName"
                        valueExpr="displayName"
                        defaultValue={selDefaultValue}
                        onSelectionChanged={onSelectionChangeds}
                        dropDownOptions={{
                          width: '350px',
                        }}
                      />
                    );
                  }
                  return <div>loading...</div>;
                }, [selDefaultValue])}
              </div>
            </div>
          </Item>
          <Item location="before">
            <div style={Divstyle}>
              <div style={Titlestyle}>统计方式:</div>
              <SelectBox
                width={120}
                items={statisticTypeData}
                displayExpr="displayName"
                valueExpr="displayName"
                value={statisticType}
                defaultValue="按汇总方式"
                onSelectionChanged={onSelectionChangedStatistic}
              />
            </div>
          </Item>
          <Item location="after">
            <AgeCalcButton
              dbname={dbname}
              accountYear={accountYear ? accountYear : accountYearRef.current}
              statisticType={statisticType}
              calcLoading={calcLoading}
              accountYearData={accountYearData}
              progressInfo={progressInfo}
              startAndEndYear={startAndEndYear}
              onOK={() => {
                onCalcOk();
              }}
            />
          </Item>
          <Item location="after">
            <Button
              type="primary"
              size="middle"
              className="invAge-setting-btn"
              icon={<SettingOutlined />}
              onClick={() => {
                invAgeConfigRef.current.showPupop();
              }}
            >
              设置库龄段
            </Button>
          </Item>
        </DevToolBar.Default>
        <div
          style={{
            flex: 1,
            overflow: 'hidden',
          }}
        >
          {useMemo(() => {
            return (
              <GridTableContainer
                AccountDataID={accountYear ? accountYear : accountYearRef.current}
                AccountTreeList={accountTreeList}
                ref={DataTreeRef}
                statisticType={statisticType}
                timeData={timeData}
                columnsData={columnsData}
                calcLoading={calcLoading}
                startAndEndYear={startAndEndYear}
              />
            );
          }, [
            accountTreeList,
            timeData,
            statisticType,
            accountYear,
            columnsData,
            progressInfo,
            calcLoading,
            startAndEndYear,
          ])}
        </div>

        {/* 库龄设置 */}
        <AgeConfigButton
          ref={invAgeConfigRef}
          reloadDevTable={() => {
            reloadTreeAndTable();
          }}
        />
      </div>
    </AgeContext.Provider>
  );
};

export default InventoryAgeAnalysis;
